package test;

import java.io.File;
import java.io.FileInputStream;
import java.util.LinkedList;
import java.util.List;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.CharacterRun;
import org.apache.poi.hwpf.usermodel.Range;

public class ODocument {
	private HWPFDocument doc;
	private String path;         //文档路径
	private List<Integer> fontSize;  //文档字体
	private List<Integer> color;     //文档颜色
	
	public ODocument(String path){
		this.doc = null;
		fontSize = new LinkedList<>();
		color = new LinkedList<>();
		this.path = path;
		this.loadDoc();
	}
	
	private void loadDoc(){  //加载文档
		try{
			FileInputStream in=new FileInputStream(new File(this.path)); 
			this.doc = new HWPFDocument(in); 
			in.close();
		}
		catch(Exception e){
			System.out.println(e.getMessage());
		}
	}
	
	public HWPFDocument getDocument(){  //返回文档对象
		return this.doc;
	}
	
	public String readDoc(){  //遍历文档，读取文档所有信息
		String Data = "";
		int length = doc.characterLength();
		String str="";
		char ch;
		int len;
		for (int i = 0; i < length - 1; i++) {
			  Range r = new Range(i,i+1,doc);
			  CharacterRun cr = r.getCharacterRun(0);
			  str = cr.text();
			  Data = Data+str;
			  len = cr.text().length();
			  color.add(cr.getColor());
			  fontSize.add(cr.getFontSize());
			  while(len-->0) ch = str.charAt(len);
		}
		System.out.println(Data);
		return DataPretreatment(Data);
	}
	
	private String DataPretreatment(String Data){  // 数据预处理，替换图片，表格，公式等为特殊字符
		Data = Data.replaceAll("(\u0013.{1,30}\u0015)+","\u0002");  //公式替换成 \u0002
		Data = Data.replaceAll("\\b.+\u0007","@TABLE@");   //表格替换为 @TABLE@ 特殊标记
		return Data;										//图片的标记是\u0001 （读取到的数据就是它，不用替换，一个标记代表一张图）
	}
	
	
}
